package com.example.qqviewspringboot.service;

import com.example.qqviewspringboot.data.User;
import com.example.qqviewspringboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Value("${avatar.storage.path}")
    private String avatarStoragePath;

    @Value("${avatar.base.url}")
    private String avatarBaseUrl;

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 注册用户
    @Override
    public User registerUser(User user) {
        if (userRepository.findByUsername(user.getUsername()).isPresent()) {
            throw new RuntimeException("用户名已存在");
        }
        return userRepository.save(user);
    }

    // 登录用户
    @Override
    public Optional<User> loginUser(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }

    // 获取用户信息
    @Override
    public Optional<User> getUserInfo(Long userId) {
        return userRepository.findById(userId);
    }

    // 更新用户名
    @Override
    public void updateUserInfo(Long userId, String newUsername) {
        Optional<User> userOptional = userRepository.findById(userId);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            // 检查新用户名是否已被使用
            if (newUsername != null && !newUsername.equals(user.getUsername()) &&
                    userRepository.findByUsername(newUsername).isPresent()) {
                throw new RuntimeException("新用户名已被占用");
            }
            if (newUsername != null) {
                user.setUsername(newUsername);
            }
            userRepository.save(user);
        } else {
            throw new RuntimeException("用户未找到");
        }
    }

    // 更新用户头像
    @Override
    public void updateUserAvatar(Long userId, String avatarUri) {
        Optional<User> userOptional = userRepository.findById(userId);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            user.setAvatarUri(avatarUri);
            userRepository.save(user);
        } else {
            throw new RuntimeException("用户未找到");
        }
    }

    // 获取所有用户列表
    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 根据用户ID获取用户名
    @Override
    public String getUserNameById(Long userId) {
        Optional<User> userOptional = userRepository.findById(userId);
        return userOptional.map(User::getUsername).orElse("Unknown User");
    }

    /**
     * 上传用户头像
     *
     * @param userId 用户ID
     * @param file   头像文件
     * @return 上传后的头像URL
     */
    @Override
    public String uploadAvatar(Long userId, MultipartFile file) {
        // 校验文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件为空");
        }

        // 获取用户
        Optional<User> optionalUser = userRepository.findById(userId);
        if (!optionalUser.isPresent()) {
            throw new IllegalArgumentException("用户不存在");
        }
        User user = optionalUser.get();

        // 创建头像目录如果不存在
        Path storagePath = Paths.get(avatarStoragePath).toAbsolutePath().normalize();
        try {
            Files.createDirectories(storagePath);
        } catch (IOException e) {
            throw new RuntimeException("无法创建存储目录", e);
        }

        // 生成唯一的文件名
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = "";

        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex >= 0) {
            fileExtension = originalFilename.substring(dotIndex);
        }

        String filename = "avatar_" + userId + "_" + System.currentTimeMillis() + fileExtension;

        // 保存文件到服务器
        Path targetLocation = storagePath.resolve(filename);
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("保存文件失败", e);
        }

        // 生成头像URL
        String avatarUrl = avatarBaseUrl + filename;

        // 更新用户的avatarUri
        user.setAvatarUri(avatarUrl);
        userRepository.save(user);

        return avatarUrl;
    }

    /**
     * 上传用户背景图片
     *
     * @param userId 用户ID
     * @param file   背景图片文件
     * @return 上传后的背景图片URL
     */
    @Override
    public String uploadBackground(Long userId, MultipartFile file) {
        // 校验文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件为空");
        }

        // 获取用户
        Optional<User> optionalUser = userRepository.findById(userId);
        if (!optionalUser.isPresent()) {
            throw new IllegalArgumentException("用户不存在");
        }
        User user = optionalUser.get();

        // 创建背景图片目录如果不存在
        Path storagePath = Paths.get(avatarStoragePath).toAbsolutePath().normalize(); // 使用相同的目录，或另设
        try {
            Files.createDirectories(storagePath);
        } catch (IOException e) {
            throw new RuntimeException("无法创建存储目录", e);
        }

        // 生成唯一的文件名
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = "";

        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex >= 0) {
            fileExtension = originalFilename.substring(dotIndex);
        }

        String filename = "background_" + userId + "_" + System.currentTimeMillis() + fileExtension;

        // 保存文件到服务器
        Path targetLocation = storagePath.resolve(filename);
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("保存文件失败", e);
        }

        // 生成背景图片URL
        String backgroundUrl = avatarBaseUrl + filename; // 如果背景有单独的URL前缀，请更改

        // 更新用户的backgroundUri
        user.setBackgroundUri(backgroundUrl);
        userRepository.save(user);

        return backgroundUrl;
    }

    /**
     * 根据用户ID获取User对象
     *
     * @param userId 用户ID
     * @return User对象
     */
    @Override
    public User getUserById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
    }

    // 如果需要上传背景图片，可以在此添加类似的方法
}
